package cn.est.controller;


import cn.est.constants.Constants;
import cn.est.dto.Result;
import cn.est.service.SmsLogService;
import cn.est.utils.ResultUtils;
import cn.est.utils.reids.RedisKeyUtils;
import cn.est.utils.reids.RedisUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

/**
 * <p>
 * 短信记录 前端控制器
 * </p>
 *
 * @author qf
 * @since 2021-08-04
 */
@RestController
@RequestMapping("/api/sms")
public class SmsLogController {

    private final RedisUtils redisUtils;
    private final SmsLogService smsLogService;

    public SmsLogController(RedisUtils redisUtils, SmsLogService smsLogService) {
        this.redisUtils = redisUtils;
        this.smsLogService = smsLogService;
    }

    @PostMapping("verifyCode")
    public Result verifyCode(String phone, Integer codeType) {
        Result result = null;
        // 1.校验手机号
        if (!phone.matches(Constants.PHONE_REGSTR)) {
            return ResultUtils.returnFail("手机号码错误");
        }

        // 2.验证验证码类型是否正确
        if (!this.checkCodeType(codeType)) {
            return ResultUtils.returnFail("验证码类型错误");
        }

        // 3.验证码发送频率
        if (!this.checkSmsCode(phone, codeType)) {
            return ResultUtils.returnFail("请勿重复发送");
        }

        // 发送短信
        smsLogService.sendMsg(phone, codeType);
        result = ResultUtils.returnSuccess();

        return result;
    }

    // 2.验证验证码类型是否正确
    private boolean checkCodeType(Integer codeType) {
        boolean flag = false;
        if (codeType != null || (codeType.equals(Constants.Sms.TYPE_UP_PASS)||
                codeType.equals(Constants.Sms.TYPE_REGIST_OR_LOGIN) ||
                codeType.equals(Constants.Sms.TYPE_NOTICE) ||
                codeType.equals(Constants.Sms.TYPE_SUBMIT_CHECK)
        )) {
            flag = true;
        }
        return flag;
    }

    // 3.验证码发送频率
    private boolean checkSmsCode(String phone, Integer codeType) {
        boolean flag = false;
        // 1.拼接前缀
        String key = RedisKeyUtils.formatKeyWithPrefix(Constants.Redis.PREFIX_SMS, codeType.toString(), phone);
        // 2.从redis取值
        String value = redisUtils.getValue(key);
        // 3.redis中不存在，说明过了有效期，可以发送
        if (StringUtils.isBlank(value)) {
            flag = true;
        }
        return flag;
    }

}

